﻿using UnityEngine;
using System.Collections;


enum GameState
{
    Playing,
    MainMenu
}

public class Player : MonoBehaviour
{
    public LayerMask placementLayerMask;
    public LayerMask towerLayerMask;
    public Material hoverMaterial;
    public GameObject[] structures;

    private GameState currentGameState;

    private LevelMaster levelMaster;
    private StatManager statManager;
    private GameObject ghostTower;
    private GameObject lastHitPlacement;
    private Turret.Turret lastHitTower;
    private Material originalMaterial;
    private int structureIndex;

    private bool readyToBuild;

	// Use this for initialization
    void Start()
    {
        levelMaster = GameObject.FindGameObjectWithTag("LevelMaster").GetComponent<LevelMaster>();
        statManager = GameObject.FindGameObjectWithTag("StatManager").GetComponent<StatManager>();
        currentGameState = GameState.MainMenu;

        readyToBuild = false;


        EventManager <EndLevelStat>.AddListener("end level", onLevelEnd);
        EventManager<Level>.AddListener("set level", onSetLevel);
        EventManager.AddListener("start level", onStartLevel);
	}
	
	// Update is called once per frame
	void Update () 
    {
        switch (currentGameState)
        {
            case GameState.Playing:
                //Build a ray at the mouse position
                Ray rayPlacement = Camera.main.ScreenPointToRay(Input.mousePosition);
                RaycastHit hitPlacement;
                //Cast the ray and check if it collide with something in the placementPlace's layer
                //The cast is made on hover for placement indication on the grid
                if (Physics.Raycast(rayPlacement, out hitPlacement, 1000, placementLayerMask))
                {
                    if (ghostTower)
                    {
                        ghostTower.GetComponent<Turret.Turret>().setActive(true);
                    }
                    //Give it's original material to the last object saved as lastHitPlacement
                    if (lastHitPlacement)
                    {
                        lastHitPlacement.renderer.material = originalMaterial;
                    }
                    //If a tower is selected, create it and place it on the placementPlace and show it's radius
                    if (structureIndex != -1 && ghostTower)
                    {
                        //move the ghost tower
                        ghostTower.transform.position = hitPlacement.collider.transform.position;
                    }
                    //Update the lastHitPlacement to the new placementPlace that collided with the ray
                    lastHitPlacement = hitPlacement.collider.gameObject;
                    //Save its original material and update it with the hover material
                    originalMaterial = lastHitPlacement.renderer.material;
                    lastHitPlacement.renderer.material = hoverMaterial;
                }
                else
                {
                    if (ghostTower)
                    {
                        ghostTower.GetComponent<Turret.Turret>().setActive(false);
                    }
                    //If nothing collides the mouse is out of the grid, reset the material and set the lastHitPlacement to null
                    if (lastHitPlacement)
                    {
                        lastHitPlacement.renderer.material = originalMaterial;
                        lastHitPlacement = null;
                    }
                }
                if (Input.GetMouseButtonDown(0))
                {
                    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                    RaycastHit hit;
                    //Cast the ray and check if it collide with something in the placementPlace's layer
                    if (readyToBuild && ghostTower)
                    {
                        if (Physics.Raycast(ray, out hit, 1000, placementLayerMask))
                        {
                            //If the clicked placementPlace is open
                            if (hit.collider.tag == "PlacementPlane_open" && structureIndex != -1)
                            {
                                levelMaster.build(ghostTower, lastHitPlacement.gameObject);
                            }
                        }
                        else
                        {
                            exitBuild();
                        }
                    }
                    else
                    {
                        //If the player hover a tower when clic and he is not building
                        if (Physics.Raycast(ray, out hit, 1000, towerLayerMask))
                        {
                            //If anoth tower is already selected
                            if (lastHitTower)
                            {
                                //Hide the radius before showing the new one
                                lastHitTower.deselectMe();
                            }
                            //Get the new tower
                            lastHitTower = hit.collider.gameObject.GetComponent<Turret.Turret>();
                            //Show it's radius
                            lastHitTower.selectMe();
                        }
                    }
                }
                break;

            case GameState.MainMenu:

                break;
        }
    }

    void OnGUI()
    {
        switch (currentGameState)
        {
            case GameState.Playing:
                if (GUI.Button(new Rect(1 * 60 - 50, Screen.height - 60, 50, 50), new GUIContent("Basic", "basic tower info")))
                {
                    startBuild(0);
                }
                if (GUI.Button(new Rect(2 * 60 - 50, Screen.height - 60, 50, 50), new GUIContent("SAM", "SAM tower info")))
                {
                    startBuild(1);
                }
                if (GUI.Button(new Rect(3 * 60 - 50, Screen.height - 60, 50, 50), new GUIContent("Rotative", "Rotative tower info")))
                {
                    startBuild(2);
                }
                if(GUI.tooltip != "")
                {
                    Stat stat = statManager.BasicTurretStat[0];
                    if (GUI.tooltip == "basic tower info")
                    {
                        stat = statManager.BasicTurretStat[0];
                    }
                    else if (GUI.tooltip == "SAM tower info")
                    {
                        stat = statManager.SAMTurretStat[0];
                    }
                    else if (GUI.tooltip == "Rotative tower info")
                    {
                        stat = statManager.RotativeTurretStat[0];
                    }
                    GUI.Label(new Rect(2 * 60 - 50, Screen.height - 150, 100, 100), statManager.statToPrint(stat));
                }

                break;

            case GameState.MainMenu:

                break;
        }
    }

    private void exitBuild()
    {
        readyToBuild = false;
        ToggleBuildPanel();
        Destroy(ghostTower.gameObject);
    }

    private void startBuild(int index)
    {
        readyToBuild = true;
        structureIndex = index;
        ghostTower = (GameObject)Instantiate(structures[structureIndex], transform.position, Quaternion.identity);
        ghostTower.GetComponent<Turret.Turret>().showRadius();
        ToggleBuildPanel();
    }

    public void ToggleBuildPanel()
    {
        //If the panel was open when clicking, it has to be closed
        levelMaster.ToggleBuildPanel(readyToBuild);
    }

    private void onSetLevel(Level level)
    {

    }


    private void onStartLevel()
    {
        currentGameState = GameState.Playing;
    }

    private void onLevelEnd(EndLevelStat stat)
    {
        currentGameState = GameState.MainMenu;
    }        

}
